package com.xiong.wuliao.HomeIntelligent;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.xiong.wuliao.R;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 图灵机器人页面
 */
public class IntelligentActivity extends AppCompatActivity {
	private ListView mMsgs;
	private ChatMessageAdapter adapter;
	private List<ChatMessage> mData;
	private ImageButton myButtonIntelligentBack; // 返回按钮

	private EditText mInputMsg;
	private Button mSendMsg;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			ChatMessage fromMessage = (ChatMessage) msg.obj;
			mData.add(fromMessage);
			adapter.notifyDataSetChanged();
			if (mData.size() != 0){
				mMsgs.setSelection(mData.size());
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IntelligentActivity.this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_intelligent);
		init();
	}

	private void init() {
		initView();
		initData();
		initListener();
	}

	private void initListener() {
		mSendMsg.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				final String toMsg = mInputMsg.getText().toString();
				if (TextUtils.isEmpty(toMsg)) {
					// 空消息不做处理
					return;
				}

				ChatMessage toMessage = new ChatMessage();
				toMessage.setDate(new Date());
				toMessage.setType(ChatMessage.Type.OUTCOMING);
				toMessage.setMsg(toMsg);
				mData.add(toMessage);
				adapter.notifyDataSetChanged();
				if (mData.size() != 0){
					mMsgs.setSelection(mData.size());
				}
				mInputMsg.setText("");

				new Thread() {
					@Override
					public void run() {
						ChatMessage fromMessage = HttpUtil.sendMessage(toMsg);
						Message message = Message.obtain();
						message.obj = fromMessage;
						mHandler.sendMessage(message);
					}
				}.start();

			}
		});
		myButtonIntelligentBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				IntelligentActivity.this.finish();
			}
		});
	}

	private void initData() {
		mData = new ArrayList<>();
		ChatMessage m = new ChatMessage();
		m.setMsg("你好啊，主人");
		m.setType(ChatMessage.Type.INCOMING);
		m.setDate(new Date());
		mData.add(m);
		adapter = new ChatMessageAdapter(IntelligentActivity.this, mData);
		mMsgs.setAdapter(adapter);
	}

	private void initView() {
		myButtonIntelligentBack = (ImageButton) findViewById(R.id.myButtonIntelligentBack);
		mMsgs = (ListView) findViewById(R.id.id_lv_msg);
		mInputMsg = (EditText) findViewById(R.id.id_input_msg);
		mSendMsg = (Button) findViewById(R.id.id_send_msg);
	}
}
